import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Col, Form, Icon, message, Modal, Radio, Row, Select, Spin, Tooltip, Typography } from 'antd';
import uniqueId from 'lodash/uniqueId';
import classNames from 'classnames';

import If from '@/components/If';
import { isSuccess } from '@/utils/request';
import { SearchInput } from '@/components/UserForm';
import OrganizationSelect from '@/components/OrganizationSelect';

import { getFunctionalList } from '@/services/Organization/orgmanage';
import {
    feedbackAssignType,
    feedbackAssignTypeEnum,
    feedbackAutoAssignType,
    feedbackAutoAssignTypeEnum
} from '@/pages/SalaryManage/enum';
import { getAssignType, saveAssignType } from '@/services/salaryManage/salaryConfirm';
import { queryFeedbackEmployeeList } from '@/services/salaryManage/salaryCommon';
import style from '@/pages/SalaryManage/SalaryConfirm/SalaryFeedback/index.less';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

const { Text } = Typography;
const { Option } = Select;
const radioStyle = {
    display: 'block',
    height: '39px',
    lineHeight: '39px'
};

let formListIndex = -1;
const AssignTypeModal = Form.create()(({ form, visible, onOk, onCancel, organizationCode }) => {
    const [model, setModel] = useState({});
    const [modalLoading, setModalLoading] = useState(false);
    const [feedbackReceiverList, setFeedbackReceiverList] = useState(null);
    const [treeDataList, setTreeDataList] = useState(null);
    const [employeeDataList, setEmployeeDataList] = useState([]);

    const getFormFeedbackReceiverList = useCallback(() => form.getFieldsValue()[formListIndex].feedbackReceiverList, [
        formListIndex
    ]);

    const addFeedbackReceiver = useCallback(() => {
        const oldFeedbackReceiverList = getFormFeedbackReceiverList();
        formListIndex += 1;
        setFeedbackReceiverList(
            [].concat(oldFeedbackReceiverList).concat({
                v_key: uniqueId(),
                receiver: null,
                departmentInfo: null
            })
        );
    }, [feedbackReceiverList, formListIndex]);

    const deleteFeedbackReceiver = useCallback(
        index => {
            if (feedbackReceiverList.length === 1) {
                message.warn('至少保留一组接收人信息');
                return;
            }
            const oldFeedbackReceiverList = getFormFeedbackReceiverList();
            // 移除给定位置元素
            oldFeedbackReceiverList.splice(index, 1);
            formListIndex += 1;
            // 使用concat方法创建一个新的对象，不然引用不变不会重新渲染
            setFeedbackReceiverList([].concat(oldFeedbackReceiverList));
        },
        [feedbackReceiverList, formListIndex]
    );

    const handleOk = () => {
        form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                return;
            }
            Object.assign(values, {
                feedbackReceiverList: getFormFeedbackReceiverList()
            });
            onOk(values, form, model, setModalLoading);
        });
    };

    const validateRule = useMemo(
        () => ({
            receivers: [
                {
                    required: true,
                    validator: (rule, value, callback) => {
                        const formValue = form.getFieldsValue();

                        // 分配方式为自动分配，且自动分配方式为平均分配时为必填
                        if (
                            formValue.assignType === feedbackAssignType.AUTO &&
                            formValue.autoAssignType === feedbackAutoAssignType.EQUAL &&
                            (!formValue.receivers || formValue.receivers.length === 0)
                        ) {
                            callback(new Error(rule.message));
                            return;
                        }
                        callback();
                    },
                    message: '请选择接收人'
                }
            ],
            receiverListReceiver(index) {
                return [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            const formValue = form.getFieldsValue();
                            const receiverList = getFormFeedbackReceiverList();

                            // 分配方式为自动分配，且自动分配方式为平均分配时为必填
                            if (
                                formValue.assignType === feedbackAssignType.AUTO &&
                                formValue.autoAssignType === feedbackAutoAssignType.DEPARTMENT &&
                                !receiverList[index].receiver
                            ) {
                                callback(new Error(rule.message));
                                return;
                            }
                            callback();
                        },
                        message: '请选择接收人'
                    }
                ];
            },
            receiverListDepartmentCodeList(index) {
                return [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            const formValue = form.getFieldsValue();
                            const receiverList = getFormFeedbackReceiverList();
                            const { departmentCodeList } = receiverList[index];

                            // 分配方式为自动分配，且自动分配方式为部门分配时为必填
                            if (
                                formValue.assignType === feedbackAssignType.AUTO &&
                                formValue.autoAssignType === feedbackAutoAssignType.DEPARTMENT &&
                                (!departmentCodeList || departmentCodeList.length === 0)
                            ) {
                                callback(new Error(rule.message));
                                return;
                            }
                            callback();
                        },
                        message: '请选择负责组织机构'
                    }
                ];
            }
        }),
        []
    );

    useEffect(() => {
        // 获取组织机构数据
        getFunctionalList({
            organizationPermissions: 1,
            showTreeFlag: 1, // 显示树结构
            auditStatus: 2
        }).then(response => {
            setTreeDataList(response);
        });
    }, []);

    useEffect(() => {
        if (organizationCode) {
            // 获取员工数据
            queryFeedbackEmployeeList({ organizationCode }).then(response => {
                const result = isSuccess(response) ? response.data || [] : [];

                // 过滤掉不可用
                setEmployeeDataList(result);
            });
        }
    }, [organizationCode]);

    useEffect(() => {
        if (organizationCode) {
            setModalLoading(true);
            getAssignType(organizationCode)
                .then(response => {
                    if (isSuccess(response)) {
                        const initModel = response.data;
                        const initReceiverList = initModel.feedbackReceiverList;

                        setModel(initModel);
                        console.log('initModel:', initModel);
                        formListIndex += 1;
                        if (initReceiverList && initReceiverList.length > 0) {
                            setFeedbackReceiverList(
                                initReceiverList.map(item => ({
                                    v_key: item.id,
                                    ...item
                                }))
                            );
                        } else {
                            setFeedbackReceiverList([
                                {
                                    v_key: uniqueId(),
                                    receiver: null,
                                    departmentCodeList: null
                                }
                            ]);
                        }
                    }
                })
                .finally(() => setModalLoading(false));
        }
    }, [organizationCode]);

    return (
        <Modal
            title={
                <>
                    分配方式配置
                    <Text type="secondary" className={salaryStyle.ml8} style={{ fontSize: 12 }}>
                        设置后即可生效，包含待分配
                    </Text>
                </>
            }
            visible={visible}
            onOk={handleOk}
            onCancel={onCancel}
            width={720}
        >
            <Spin spinning={modalLoading}>
                <Form layout="horizontal">
                    <Form.Item label="分配方式" className={classNames(salaryStyle.flex, style.assignLabelItem)}>
                        <span>
                            {form.getFieldDecorator('assignType', {
                                initialValue: model.assignType ?? feedbackAssignType.MANUAL
                            })(
                                <Radio.Group>
                                    <Radio value={feedbackAssignType.MANUAL} style={radioStyle}>
                                        {/* 手动分配 */}
                                        {feedbackAssignTypeEnum.getShowName(feedbackAssignType.MANUAL)}
                                    </Radio>
                                    <Radio value={feedbackAssignType.AUTO} style={radioStyle}>
                                        {/* 自动分配 */}
                                        {feedbackAssignTypeEnum.getShowName(feedbackAssignType.AUTO)}
                                        <If condition={form.getFieldValue('assignType') === feedbackAssignType.AUTO}>
                                            <Form.Item
                                                colon={false}
                                                label=" "
                                                labelCol={{ span: 0 }}
                                                className={style.assignRadioItem}
                                            >
                                                {form.getFieldDecorator('autoAssignType', {
                                                    initialValue: model.autoAssignType ?? feedbackAutoAssignType.EQUAL
                                                })(
                                                    <Select>
                                                        <Option value={feedbackAutoAssignType.EQUAL}>
                                                            {feedbackAutoAssignTypeEnum.getShowName(
                                                                feedbackAutoAssignType.EQUAL
                                                            )}
                                                        </Option>
                                                        <Option value={feedbackAutoAssignType.DEPARTMENT}>
                                                            {feedbackAutoAssignTypeEnum.getShowName(
                                                                feedbackAutoAssignType.DEPARTMENT
                                                            )}
                                                        </Option>
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </If>
                                    </Radio>
                                </Radio.Group>
                            )}
                        </span>
                    </Form.Item>
                    <If
                        condition={
                            form.getFieldValue('assignType') === feedbackAssignType.AUTO &&
                            form.getFieldValue('autoAssignType') === feedbackAutoAssignType.EQUAL
                        }
                    >
                        <Form.Item label="接收人" className={classNames(salaryStyle.flex, style.assignLabelItem)}>
                            <span>
                                {form.getFieldDecorator('receivers', {
                                    initialValue: model.receivers,
                                    rules: validateRule.receivers
                                })(
                                    <SearchInput
                                        params={{
                                            employeeDataList
                                        }}
                                        getData={async () =>
                                            // 过滤掉不可用
                                            employeeDataList.filter(
                                                item => !item.disabled || model?.receivers?.includes(item.employeeCode)
                                            )
                                        }
                                        selectProps={{
                                            placeholder: '请输入员工姓名',
                                            allowClear: true,
                                            mode: 'multiple',
                                            style: {
                                                width: 475
                                            }
                                        }}
                                        fieldsName={{
                                            value: 'employeeCode',
                                            title: 'name'
                                        }}
                                    />
                                )}
                            </span>
                        </Form.Item>
                    </If>
                    <If
                        condition={
                            form.getFieldValue('assignType') === feedbackAssignType.AUTO &&
                            form.getFieldValue('autoAssignType') === feedbackAutoAssignType.DEPARTMENT
                        }
                    >
                        {feedbackReceiverList
                            ? feedbackReceiverList.map((feedbackReceiver, index) => (
                                <Row type="flex" gutter={10} key={feedbackReceiver.v_key}>
                                    <Col span={10}>
                                        <Tooltip title="默认接收人">
                                            <Form.Item
                                                label="接收人"
                                                className={classNames(salaryStyle.flex, style.assignLabelItem)}
                                              >
                                                <span>
                                                    {form.getFieldDecorator(
                                                          `[${formListIndex}]feedbackReceiverList[${index}].receiver`,
                                                          {
                                                              initialValue: feedbackReceiver.receiver || undefined,
                                                              rules: validateRule.receiverListReceiver(index)
                                                          }
                                                      )(
                                                          <SearchInput
                                                              params={{
                                                                  employeeDataList
                                                              }}
                                                              getData={async () =>
                                                                  // 过滤掉不可用
                                                                  employeeDataList.filter(
                                                                      item =>
                                                                          !item.disabled ||
                                                                          item.employeeCode ===
                                                                              feedbackReceiver.receiver
                                                                  )
                                                              }
                                                              selectProps={{
                                                                  placeholder: '请输入员工姓名',
                                                                  allowClear: true
                                                              }}
                                                              fieldsName={{
                                                                  value: 'employeeCode',
                                                                  title: 'name'
                                                              }}
                                                              style={{ width: '100%' }}
                                                          />
                                                      )}
                                                </span>
                                            </Form.Item>
                                        </Tooltip>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="负责组织机构" className={salaryStyle.flex}>
                                            {form.getFieldDecorator(
                                                  `[${formListIndex}]feedbackReceiverList[${index}].departmentCodeList`,
                                                  {
                                                      initialValue: feedbackReceiver.departmentCodeList,
                                                      rules: validateRule.receiverListDepartmentCodeList(index)
                                                  }
                                              )(
                                                  <OrganizationSelect
                                                      treeCheckable
                                                      isFunctional
                                                      isStrictly
                                                      strictlyOutType="string"
                                                      maxTagCount={2}
                                                      treeDataFromProp
                                                      treeDataList={treeDataList}
                                                  />
                                              )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={4}>
                                        <Row>
                                            <If condition={feedbackReceiverList.length !== 1}>
                                                <Col span={12} className={salaryStyle.textCenter}>
                                                    <Tooltip title="删除">
                                                        <Button
                                                            className={classNames(
                                                                  salaryStyle.operateIcon,
                                                                  style.assignItemButton
                                                              )}
                                                            onClick={() => deleteFeedbackReceiver(index)}
                                                          >
                                                            <Icon type="minus-circle" />
                                                        </Button>
                                                    </Tooltip>
                                                </Col>
                                            </If>

                                            <If condition={index + 1 === feedbackReceiverList.length}>
                                                <Col span={12} className={salaryStyle.textCenter}>
                                                    <Tooltip title="新增接收人和负责部门">
                                                        <Button
                                                            className={classNames(
                                                                  salaryStyle.operateIcon,
                                                                  style.assignItemButton
                                                              )}
                                                            onClick={addFeedbackReceiver}
                                                          >
                                                            <Icon type="plus-circle" />
                                                        </Button>
                                                    </Tooltip>
                                                </Col>
                                            </If>
                                        </Row>
                                    </Col>
                                </Row>
                              ))
                            : null}
                    </If>
                </Form>
            </Spin>
        </Modal>
    );
});
AssignTypeModal.displayName = 'AssignTypeModal';

/**
 * 分配方式
 * @param organizationCode 行政机构
 * @param search
 * @returns {JSX.Element|{onShowAssignType: onShowAssignType, onAssignType: onAssignType, render(): *}}
 */
const useAssignType = (organizationCode, search) => {
    // 显示分配方式设置
    const [showAssignType, setShowAssignType] = useState(false);

    // 展示分配方式
    const onShowAssignType = () => {
        setShowAssignType(true);
    };
    // 设置分配方式
    const onAssignType = (formValues, form, model, setModalLoading) => {
        form.validateFieldsAndScroll(errors => {
            if (errors) {
                message.warn('请正确填写信息');
                return;
            }
            const { feedbackReceiverList, ...postData } = formValues;
            postData.id = model.id;

            if (!postData.organizationCode) {
                postData.organizationCode = organizationCode;
            }

            if (
                postData.assignType === feedbackAssignType.AUTO &&
                postData.autoAssignType === feedbackAutoAssignType.DEPARTMENT &&
                feedbackReceiverList &&
                feedbackReceiverList.length > 0
            ) {
                // 清除【平均分配】的【接收人】
                postData.receivers = null;
                postData.feedbackReceiverList = feedbackReceiverList.map(item => {
                    const { departmentCodeList, ...otherInfo } = item;

                    return { ...otherInfo, departmentCodeList };
                });
            }

            if (
                postData.assignType === feedbackAssignType.AUTO &&
                postData.autoAssignType === feedbackAutoAssignType.EQUAL &&
                postData.receivers &&
                postData.receivers.length > 0
            ) {
                // 清除【按部门分配】的新增信息
                postData.feedbackReceiverList = null;
            }

            setModalLoading(true);
            saveAssignType(postData)
                .then(response => {
                    if (!isSuccess(response)) {
                        message.error(response.msg);
                        return;
                    }
                    message.success('保存成功！');
                    search();
                    setShowAssignType(false);
                })
                .finally(() => setModalLoading(false));
        });
    };

    return {
        onShowAssignType,
        onAssignType,
        render() {
            return (
                <>
                    <If condition={showAssignType}>
                        <AssignTypeModal
                            visible={showAssignType}
                            onOk={onAssignType}
                            onCancel={() => setShowAssignType(false)}
                            organizationCode={organizationCode}
                        />
                    </If>
                </>
            );
        }
    };
};

export default useAssignType;
